//
//  TimingView.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/2/23.
//

import SwiftUI
import AudioToolbox

fileprivate let kTimingBtnWH: CGFloat = 100

struct TimingView: View {
    @Environment(\.presentationMode) var presentationMode
    
    @StateObject private var viewModel = TimingViewModel()
    @State private var groupId: String = UUID().uuidString
    
    var caTimer: CATimer
    
    var body: some View {
        VStack {
            TimingStartView(caTimer: caTimer, groupId: groupId, viewModel: viewModel)
            
            let needRecordTime = caTimer.type == TimerType.scheduleTime.id
            
            List {
                HStack {
                    TimeRecordItem(title: "名称")
                    Spacer()
                    TimeRecordItem(title: "分段")
                    Spacer()
                    TimeRecordItem(title: "累计")
                    if needRecordTime {
                        Spacer()
                        TimeRecordItem(title: "时间")
                    }
                }
                .hideListRowSeperator()
                
                ForEach(viewModel.items, id: \.uuid) { record in
                    SplitTimeCell(record: record, needRecordTime: needRecordTime)
                }
                .hideListRowSeperator()
            }
            .onAppear(perform: {
                viewModel.loadCATimer(groupId: groupId)
            })
            .toolbar {
                ToolbarItem {
                    NavigationLink(destination: EditTimerView()) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            .listStyle(.plain)
        }
        .padding(.top, -20)
    }
}

struct TimingStartView: View {
    @State private var isTiming: Bool = false
    /// 累计秒数
    @State private var totalSeconds: Int = 0
    /// 上一次累计的秒数
    @State private var lastTotalSeconds: Int = 0
    @State private var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    @State private var btn1Color = Color.green
    @State private var btn1Title = "启动"
    @State private var btn2Color = Color.gray
    @State private var startTimeStr: String = ""
    @State private var startTime: TimeInterval = 0
    @State private var times: Int = 0
    
    var caTimer: CATimer
    var groupId: String
    var viewModel: TimingViewModel
    
    var body: some View {
        Text(startTimeStr)
            .font(Font.system(size: 50))
            .onReceive(timer, perform: { _ in
                if isTiming {
                    startTime += 1
                    totalSeconds += 1
                    showTime()
                }
            })
            .onAppear(perform: {
                startTimer()
                // 为了给 @State startTime的属性赋值
                if startTime != 0 { return }
                if caTimer.type == TimerType.scheduleTime.id {
                    startTime = caTimer.startTime
                }
                showTime()
            })
            .onDisappear(perform: {
                stopTimer()
            })
        
        if caTimer.type == TimerType.scheduleTime.id {
            Spacer(minLength: 12)
            Text("\(caTimer.endTime.formatTime("HH:mm:ss"))")
                .font(.system(size: 13))
                .foregroundColor(.secondary)
            Spacer(minLength: 12)
            Text("\(totalSeconds.toSecondStr())")
                .font(.system(size: 26))
        }
        
        Spacer(minLength: 18)
        
        HStack {
            Spacer()
            Button {
                startOrStopTimer()
            } label: {
                Text(btn1Title)
                    .foregroundColor(.white)
                    .frame(width: kTimingBtnWH, height: kTimingBtnWH)
                    .background(btn1Color)
                    .cornerRadius(kTimingBtnWH / 2)
            }
            
            Spacer(minLength: 90)
            
            Button {
                metering()
            } label: {
                Text("计次")
                    .foregroundColor(.white)
                    .frame(width: kTimingBtnWH, height: kTimingBtnWH)
                    .background(btn2Color)
                    .cornerRadius(kTimingBtnWH / 2)
            }
            
            Spacer()
        }
        
        Spacer(minLength: 25)
    }
    
    private func startOrStopTimer() {
        AudioServicesPlaySystemSound(1103)
        if isTiming {
            isTiming = false
            stopTimer()
            btn1Title = "启动"
            btn1Color = .green
            btn2Color = .gray
        } else {
            isTiming = true
            startTimer()
            btn1Title = "暂停"
            btn1Color = .orange
            btn2Color = .green
        }
    }
    
    private func startTimer() {
        timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    }
    
    private func stopTimer() {
        timer.upstream.connect().cancel()
    }
    
    // 计次
    private func metering() {
        AudioServicesPlaySystemSound(1103)
        
        times = times + 1
        let title = "计次\(times)"
        
        // 区间秒数
        let duration = abs(Int(totalSeconds - lastTotalSeconds))
        
        let record = TimeRecord(context: kStoreContext)
        record.uuid = UUID().uuidString
        record.title = title
        record.groupId = groupId
        record.duration = Double(duration)
        record.theTime = startTime
        record.theCumulativeTime = Double(totalSeconds)
        record.createTime = FNow()
        record.updateTime = FNow()
        record.timer = caTimer
        
        lastTotalSeconds = totalSeconds
        
        withAnimation {
            do {
                try kStoreContext.save()
                viewModel.loadCATimer(groupId: groupId)
            } catch {
                log.error("保存错误：\(error)")
            }
        }
    }
    
    private func showTime() {
        if caTimer.type == TimerType.scheduleTime.id {
            startTimeStr = startTime.formatTime("HH:mm:ss")
            log.verbose(startTimeStr)
        } else {
            startTimeStr = Int(startTime).toSecondStr()
        }
    }
}

struct SplitTimeCell: View {
    var record: TimeRecord
    var needRecordTime: Bool
    
    var body: some View {
        HStack {
            TimeRecordItem(title: record.title ?? "")
            Spacer()
            TimeRecordItem(title: "\(Int(record.duration).toSecondStr())")
            Spacer()
            TimeRecordItem(title: "\(Int(record.theCumulativeTime).toSecondStr())")
            if needRecordTime {
                Spacer()
                TimeRecordItem(title: "\(record.theTime.formatTime("HH:mm:ss"))")
            }
        }
    }
}

struct TimeRecordItem: View {
    var title: String
    
    var body: some View {
        Text(title)
            .font(.system(size: 17))
            .frame(width: 90, alignment: .center)
    }
}

//#Preview {
////    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \CATimer.name, ascending: true)], animation: .default)
////    var items: FetchedResults<CATimer>
////    
////    guard let timer = items.first else { return SplitTimeCell() }
//    
////    TimingView(caTimer: CATimer())
////    SplitTimeCell(groupId: "93BD4B09-AE43-4AEE-9677-0E17D19E4E05")
//}
